/**
 * CQCIS Base JS Library extend
 * 
 * @author liuhz
 */
/** 全局静态变量 **/
CQCIS.SM = {
    // 菜单根节点编码
    MENU_ROOT_CODE : '0',
    // 重庆局ID
    COMPANY_CQ_ID : '1000',
    // 重庆局nodeId
    COMPANY_CQ_NODEID : '1537',
    // 历史表数据库前缀
    ORD_TABLES_HIS : 'pf_his',
    //模板生效初始时间：（包括定单，工单等）
    ORD_EFF_TIME : '2030-01-01 00:00:00',
    //模板失效初始时间：（包括定单，工单等）
    ORD_EXP_TIME : '2050-01-01 00:00:00',
    // 版权信息
    COPYRIGHT : 'Copyright 2008-2009. Chongqing Communications Industry Services Co.,Ltd Information Technology Branch. All rights reserved.'
};


CQCIS.toString = function(o, trim){
    if (typeof o == 'string'){
        return o;
    }else{
        if (CQCIS.LIBS.indexOf("dwr") !== -1){
            return dwr.util.toDescriptiveString(o, 3, trim ? {lineTerminator:"",childIndent:""} : undefined);
        }else{
            if (trim) {
                o = Ext.urlEncode(o);
                return o.replace(/^\s*(.*?)\s+$/, "$1");
            } else {
                return Ext.urlEncode(o);
            }
        }
    }
};

CQCIS.confirm = function(msg, fn, scope) {
    Ext.Msg.show({
        title : "提示",
        msg : msg,
        buttons : Ext.Msg.YESNO,
        fn : fn,
        cls : 'dlg-top',
        minHeight : 32,
        minWidth : 200,
        scope : scope,
        icon: Ext.MessageBox.QUESTION
    });
};

CQCIS.alert = function(msg, fn, scope){
    Ext.Msg.show({
        title : "提示",
        msg : CQCIS.toString(msg),
        minHeight : 32,
        minWidth : 200,
        fn : fn,
        scope : scope || window,
        cls : 'dlg-top',
        buttons : Ext.Msg.OK
    });
};

CQCIS.closeMSG = function(o, e){
    var evt = e || event;
    var obj = evt.srcElement || evt.target;
    var msgDiv = Ext.get(obj).up('.msg');
    if (msgDiv) {
        msgDiv.setStyle({
            display: 'none'
        });
    }
};

CQCIS.msg = function(format, title){
    function createBox(t, s){
        return ['<div class="msg">',
                '<div class="x-box-tl"><div class="x-box-tr"><div class="x-box-tc"></div></div></div>',
                '<div class="x-box-ml"><div class="x-box-mr"><div class="x-box-mc"><h3 style="float:left;">',
                t,
                '</h3><a class="qtip-close" onclick="CQCIS.closeMSG(1, event);"></a>',
                '<div style="clear:both;">',
                s,
                '</div>',
                '</div></div></div>',
                '<div class="x-box-bl"><div class="x-box-br"><div class="x-box-bc"></div></div></div>',
                '</div>'].join('');
    }
    
    if(!CQCIS.msgCt){
       CQCIS.msgCt = Ext.DomHelper.insertFirst(document.body, {id:'msg-div'}, true);
    }
    
    title = title || '提示';
    format = CQCIS.toString(format);
    this.msgCt.alignTo(document.body, 't-t');
    var s = String.format.apply(String, Array.prototype.slice.call(arguments, 0));
    var m = Ext.DomHelper.append(CQCIS.msgCt, {html:createBox(title, s)}, true);
    m.slideIn('t').pause(2).ghost('t', {remove:true});
};

CQCIS.console = function(msg, level) {
    var helpInfo = top.document.getElementById("helpInfo");
    if (!helpInfo) {
        return false;
    }
    var title, now = new Date();
    switch (level) {
        case 1 :title = '<font style="color: yellow;">警告</font>';break;
        case 2 :title = '<font style="color: red;">错误</font>';break;
        case 3 :title = '<font style="color: orange;">系统</font>';break;
        default:title = '<font style="color: green;">信息</font>';break;
    }
    msg = CQCIS.toString(msg);
    var str = "<p>" + now.format('H:i:s') + " <b>[" + title + "]</b> " + msg.replace(/\n/g, "<br />") + "</p>";
    Ext.get(helpInfo).insertHtml('beforeEnd',str,false);
};

/** theme support */
Ext.ux.theme = {
    init: function(){
        var themeName = CQCIS.cookies.get('omstheme') || 'default';
        Ext.util.CSS.swapStyleSheet("theme", CQCIS.ctxPath + "/styles/ext/css/xtheme-" + themeName + ".css");
    },
    apply: function(){
        var themeName = top.themeBtn.getActiveItem().id;
        CQCIS.cookies.set("omstheme", themeName, new Date("December 31, 2070"));
        Ext.util.CSS.swapStyleSheet("theme", CQCIS.ctxPath + "/styles/ext/css/xtheme-" + themeName + ".css");
        Ext.ux.theme.changeTheme(center, center.getActiveTab());
    },
    changeTheme: function(panel, tab){
        if (tab.getFrameWindow() && tab.getFrameWindow().Ext) {
            var themeName = CQCIS.cookies.get('omstheme') || 'default';
            tab.getFrameWindow().Ext.util.CSS.swapStyleSheet("theme", CQCIS.ctxPath + "/styles/ext/css/xtheme-" + themeName + ".css");
        }
    }
};

CQCIS.cookies = {
    set : function(name, value){
         var argv = arguments;
         var argc = arguments.length;
         var expires = (argc > 2) ? argv[2] : null;
         var path = (argc > 3) ? argv[3] : '/';
         var domain = (argc > 4) ? argv[4] : null;
         var secure = (argc > 5) ? argv[5] : false;
         document.cookie = name + "=" + escape(value) +
            ((expires === null) ? "" : ("; expires=" + expires.toGMTString())) +
            ((path === null) ? "" : ("; path=" + path)) +
            ((domain === null) ? "" : ("; domain=" + domain)) +
            ((secure === true) ? "; secure" : "");
    },
    get : function(name){
        var arg = name + "=";
        var alen = arg.length;
        var clen = document.cookie.length;
        var i = 0;
        var j = 0;
        while(i < clen){
            j = i + alen;
            if (document.cookie.substring(i, j) == arg) {
                return CQCIS.cookies.getCookieVal(j);
            }
            i = document.cookie.indexOf(" ", i) + 1;
            if(i === 0) {
                break;
            }
        }
        return null;
    },  
    clear : function(name) {
      if(CQCIS.cookies.get(name)){
        document.cookie = name + "=" + "; expires=Thu, 01-Jan-70 00:00:01 GMT";
      }
    },  
    getCookieVal : function(offset){
       var endstr = document.cookie.indexOf(";", offset);
       if(endstr == -1){
           endstr = document.cookie.length;
       }
       return unescape(document.cookie.substring(offset, endstr));
    }
};

Array.prototype.findBy = function(attr, value){
    for (var i = 0; i < this.length; i++) {
        var o = this[i];
        if (o[attr] == value) {
            return o;
        }
    }
    return false;
};

if (Ext.Toolbar) {
    Ext.override(Ext.Toolbar, {
        height: 26
    });
}

if (Ext.Container) {
    Ext.override(Ext.Container, {
        monitorResize: true,
        render: function(){
            Ext.Container.superclass.render.apply(this, arguments);
            if (this.layout) {
                if (typeof this.layout == 'string') {
                    this.layout = new Ext.Container.LAYOUTS[this.layout.toLowerCase()](this.layoutConfig);
                }
                this.setLayout(this.layout);
                
                if (this.activeItem !== undefined) {
                    var item = this.activeItem;
                    delete this.activeItem;
                    this.layout.setActiveItem(item);
                    return;
                }
            }
            if (!this.ownerCt) {
                this.doLayout();
            }
            if (this.monitorResize === true) {
                Ext.EventManager.onWindowResize(this.doLayout, this, [false]);
            }
            
            this.on('afterlayout', function(){
                if (this.items) {
                    var cs = this.items.items;
                    for (var i = 0, len = cs.length; i < len; i++) {
                        var c = cs[i];
                        c.fireEvent('added', c, this);
                    }
                    this.doLayout();
                }
            }, this, {
                single: true
            });
        },
        add: function(comp){
            if (!this.items) {
                this.initItems();
            }
            var a = arguments, len = a.length;
            if (len > 1) {
                for (var i = 0; i < len; i++) {
                    this.add(a[i]);
                }
                return;
            }
            var c = this.lookupComponent(this.applyDefaults(comp));
            var pos = this.items.length;
            if (this.fireEvent('beforeadd', this, c, pos) !== false && this.onBeforeAdd(c) !== false) {
                this.items.add(c);
                c.ownerCt = this;
                if (c.hasListener('added')) {
                    c.fireEvent('added', c, this);
                }
                this.fireEvent('add', this, c, pos);
            }
            return c;
        }
    });
}

Ext.onReady(function(){
    var topPath = top.location.pathname;
    if (topPath.indexOf('index.html') == -1 && topPath.indexOf('main.html') == -1 && topPath.substr(topPath.length - 1) != '\/') {
        top.location.replace(CQCIS.ctxPath + 'index.html');
        return;
    }
    Ext.BLANK_IMAGE_URL = CQCIS.jsPath + '../styles/ext/images/default/s.gif';
    //Ext.getBody().unselectable();
    /*Ext.getBody().on('contextmenu', Ext.emptyFn, this, {
        stopEvent: true
    });*/
    if (CQCIS.LIBS.indexOf("dwr") !== -1) {
        DWREngine.setErrorHandler(function(msg, ex){
            if (msg && msg.indexOf("登录系统") >= 0) {
                CQCIS.alert(msg, function(){
                    top.logionWin.init();
                    /*if (top.userName) {
                        top.logionWin.init();
                    } else {
                        top.location.replace(CQCIS.ctxPath + 'index.html');
                    }*/
                });
            } else if (msg) {
                CQCIS.msg(msg, '远程调用失败');
                CQCIS.console(msg, 3);
                if (ex.getDetailedMessage) {
                    CQCIS.console(ex.getDetailedMessage(), 3);
                } else {
                    CQCIS.console(ex, 3);
                }
            }
        });
        DWREngine.setWarningHandler(function(msg, ex){
            CQCIS.msg(msg, '远程调用警告');
            CQCIS.console(msg, 1);
            CQCIS.console(ex, 1);
        });
    }
    Ext.ux.theme.init();
    Ext.QuickTips.init();
    // 调试时清除Cookie用
    // Ext.state.Manager.setProvider(new Ext.state.CookieProvider({expires : new Date()}));
    // Ext.state.Manager.setProvider(new Ext.state.CookieProvider());
    window.status = CQCIS.SM.COPYRIGHT;
    Ext.getBody().on('keydown', function(e, obj){
        // 屏蔽Ctrl + N（新建当前窗口）、Ctrl + R（刷新当前页面）组合键
        if (e.ctrlKey) {
            if (e.getKey() == 78 || e.getKey() == 82) {
                e.preventDefault();
                return;
            }
        }
        
        // 屏蔽Alt + 左、右箭头（前进、后退功能）
        if (e.altKey) {
            if (e.getKey() == e.LEFT || e.getKey() == e.RIGHT) {
                e.preventDefault();
                return;
            }
        }
        
        // 屏蔽Shift + F10（右键菜单）组合键
        if (e.shiftKey) {
            if (e.getKey() == 121) {
                e.preventDefault();
                return;
            }
        }
        
        // 屏蔽退格键
        if (e.getKey() == e.BACKSPACE) {
            if ((obj.nodeName != 'INPUT' && obj.nodeName != 'TEXTAREA') || obj.readOnly) {
                e.preventDefault();
                return;
            }
        }
    });
});
